<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib uri="/WEB-INF/tld/liferay-portlet.tld" prefix="portlet"%>
<%@ taglib tagdir="/WEB-INF/tags" prefix="mytag" %>

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@page import="javax.portlet.*"%>


<portlet:defineObjects />

<html>
<head>
    <script>

        var ReportDefinition = {
            saveAllowed:false,
            reports : new Array(),
            init : function(_isSchedulerVisible){
                var $tabs = $("#tabs");
                var $scheduleBtn = $("#scheduleBtn");
                $tabs.tabs({
                    show: function(event, ui) {
                        if (ui.index==3){
                            allignParameters();
                        }
                    }
                }).tabs( "select" , ~~($('#sTab').val())).css('display',"block");
                isSchedulerVisible=_isSchedulerVisible;
                if (isSchedulerVisible){
                    $tabs.tabs("enable", 5);
                    if (Scheduler.Frequency.$itm.val()!='OneTime'){
                        $(".ExplicitDerived input[value=Explicit]").attr("disabled","disabled");
                    }
                    $scheduleBtn.addClass("buttonPressed");
                    $("#selectedReportScheduler").removeClass("displayNone");
                    if ($.trim($("#scheduleDate").val())!=""){
                        $("#selectedReportScheduler .selectedReportScheduleText").text($("#"+Scheduler.Frequency.$itm.val()+"Footer").text());
                    }
                } else{
                    $tabs.tabs("disable", 5);
                    $scheduleBtn.removeClass("buttonPressed");
                    $("#selectedReportScheduler").addClass("displayNone");
                }
                $(".ExplicitDerived").show();
                $('#reporting_form').removeAttr("target");

                if ($('#isViewPressed').val() == 'true'){
                    $("#isViewPressed").val() == 'false';
                    location.href = '<portlet:resourceURL><portlet:param name="whoRuns" value="report" /></portlet:resourceURL>';
                }
                preConfig('reporting_form','reportDefinition','${HELP_URL}');
                var report;
                <c:forEach var="myreport" items="${MY_REPORTS}">
                    report=$.trim("<c:out value='${myreport.name}' />").toLowerCase();
                    if ($.trim($('#actualReportName').val().toLowerCase())!=report){
                        this.reports.push(report);
                    }
                </c:forEach>
                if($.trim($('#myReportName').val())!=""){
                    this.saveAllowed=true;
                }
                $('#myReportName').keyup(function() {
                  if ($.inArray($.trim($(this).val().toLowerCase()),ReportDefinition.reports)>-1||$.trim($('#myReportName').val())==""){
                    $(this).css('border-color','red');
                    ReportDefinition.saveAllowed=false;
                  }else{
                    $(this).css('border-color','#4F81BD');
                    ReportDefinition.saveAllowed=true;
                  }
                  $('#selectedReportName').text($.trim($(this).val()));
                });
                $scheduleBtn.click(function(){
                    $("#selectedReportScheduler").toggleClass("displayNone");
                    $(this).toggleClass("buttonPressed");
                    if ($(this).hasClass("buttonPressed")){
                        $tabs.tabs("enable", 5);
                        if (Scheduler.Frequency.$itm.val()!='OneTime'){
                            $(".ExplicitDerived input[value=Explicit]").attr("disabled","disabled");
                        }
                        isSchedulerVisible=true;
                    }else{
                        if ($tabs.tabs( "option", "selected")==5){
                            $tabs.tabs('select', 0);
                        }
                        $(".ExplicitDerived input[value=Explicit]").removeAttr("disabled");
                        $tabs.tabs("disable", 5);
                        isSchedulerVisible=false;
                    }
                    setParams();
                });
                setParams();
            }
        };

        var Scheduler = {
            Recipients : {
                $container : {},
                invalidEmails : "",
                init: function(_cont){
                    this.$container = $(_cont);
                    this.$container.keyup(function(){
                        $("#selectedReportScheduler .selectedReportRecipientsText").text($(this).val());
                        populateSelectedReport();
                    });
                },

                addRecipients : function(_val){
                    this.$container.val($.trim(this.$container.val())+_val);
                },

                getRecipients : function(){
                    return $.trim(this.$container.val());
                },

                getLoggedUserEmail : function(){
                    return this.$container.data("useremail");
                },

                isUserEmailInRecipients : function(){
                    return (this.getRecipients().toLowerCase().indexOf(this.getLoggedUserEmail().toLowerCase())==-1);
                },
                validateEmail : function(){
                    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
                    if($.trim(this)==""){return;}
                    if(reg.test($.trim(this)) == false){
                        if(Scheduler.Recipients.invalidEmails!=""){
                            Scheduler.Recipients.invalidEmails+=";";
                        }
                        Scheduler.Recipients.invalidEmails+=$.trim(this);
                        return;
                    }
                },
                areRecipientsValid : function(){
                    this.invalidEmails="";
                    $.each(this.getRecipients().split(';'),this.validateEmail);
                    return this.invalidEmails=="";
                },
                insertLoggedUserEmail : function(){
                    if (this.isUserEmailInRecipients()){
                        if (this.getRecipients()==""){
                            this.addRecipients(this.getLoggedUserEmail());
                        }else{
                            this.addRecipients(";"+this.getLoggedUserEmail());
                        }
                    }
                }
            },

            getNextDay: function(_dayNumber){
                if(_dayNumber>31){return $.datepicker.formatDate('mm/dd/yy', new Date()) }
                for (var date=new Date(); date.setDate(date.getDate()+1) && date.getDate()!=_dayNumber;){}
                return $.datepicker.formatDate('mm/dd/yy', date);
            },

            getNextDate: function(_dayOfWeekNumber){
                if(_dayOfWeekNumber>6){return $.datepicker.formatDate('mm/dd/yy', new Date()) }
                for (var date=new Date(); date.setDate(date.getDate()+1) && date.getDay()!=_dayOfWeekNumber;){}
                return $.datepicker.formatDate('mm/dd/yy', date);
            },

            setRunDateTime : function(_freq, _date, _day, _time){
                var today = new Date();
                var currTime = Date.parse(_time).toString("HH:mm");
                //var $schedulerDateFooter = $("#schedulerFooter .schedulerDateFooter");
                if(((_freq==2&&_day==today.getDay())||_date==today.getDate())&&(currTime.split(':')[0]>today.getHours()||
                    (currTime.split(':')[0]==today.getHours()&&currTime.split(':')[1]>today.getMinutes()))){
                        this.$schedulerDateFooter.text($.datepicker.formatDate('mm/dd/yy', today));
                }else{
                    switch (_freq){
                        case 1:
                            today.setDate(today.getDate()+1);
                            this.$schedulerDateFooter.text($.datepicker.formatDate('mm/dd/yy', today));
                            break;
                        case 2:
                            this.$schedulerDateFooter.text(this.getNextDate(_day));
                            break;
                        case 3:
                            this.$schedulerDateFooter.text(this.getNextDay(_date));
                            break;
                    }
                }
                this.$schedulerTimeFooter.text(_time);
            },
            MonthlyCalendar : {
                $container : $(),
                init: function(_cont){
                    this.$container = _cont;
                    this.$container.hover(
                        function () {
                            if ($(this).hasClass('monthlyCalendarLastCell')){
                                return;
                            }
                            $(this).addClass('weeksColHovered');
                        },
                        function () {
                            if ($(this).hasClass('monthlyCalendarLastCell')){
                                return;
                            }
                            $(this).removeClass('weeksColHovered');
                        }
                    );
                    this.$container.click(function(){
                        if ($(this).hasClass('monthlyCalendarLastCell')){
                            return;
                        }
                        Scheduler.MonthlyCalendar.selectDay($(this));
                        Scheduler.$recurringTime.val($(this).text());
                        Scheduler.setRunDateTime(3,$(this).attr('data-numb'),"",Scheduler.$scheduleTime.val());
                        populateSelectedReport();
                    });
                },
                deselectAllDays : function(){
                    this.$container.removeClass('weeksColSelected');
                },
                selectDay : function($day){
                    this.deselectAllDays();
                    $day.addClass('weeksColSelected');
                }
            },
            Frequency : {
                $itm : $(),
                init: function(_cont){
                    this.$itm=_cont;
                    this.$itm.change(function(args){
                        var frequencyVal = $(this).val();
                        if(frequencyVal=="OneTime"){
                            Scheduler.$scheduleTime.parent().hide();
                            Scheduler.$scheduleDate.parent().show();
                            Scheduler.$scheduleDateParam.val(Date.parse(Scheduler.$scheduleDate.val()).toString("MM/dd/yyyy HH:mm"));
                            $(".ExplicitDerived input[value=Explicit]").removeAttr("disabled");
                        }else{
                            if($("input[value=Explicit][type=radio]:checked").length>0){
                                $("#tabs").tabs('select', 3);
                                alert(ErrorMessages.CANNOT_USE_EXACT_DATES);
                            }
                            $(".ExplicitDerived input[value=Explicit]").attr("disabled","disabled");
                            $("input[value=Derived][type=radio]").click();
                            Scheduler.$scheduleDateParam.val(new Date().toString("MM/dd/yyyy")+" "+Date.parse(Scheduler.$scheduleTime.val()).toString("HH:mm"));
                            Scheduler.$scheduleTime.parent().show();
                            Scheduler.$scheduleDate.parent().hide();
                        }
                        $(".recuringRight > div").each(function() {
                            if($(this).attr('id')=="time"){return}
                            if('recuring'+frequencyVal==$(this).attr('id')){
                                $(this).show();
                            }else{
                                $(this).hide();
                            }
                        });
                        var today=new Date();
                        if(frequencyVal=='OneTime'){
                            Scheduler.$schedulerDateFooter.text(Date.parse(Scheduler.$scheduleDate.val()).toString("MM/dd/yyyy"));
                            Scheduler.$schedulerTimeFooter.text(Date.parse(Scheduler.$scheduleDate.val()).toString("hh:mm tt").toLowerCase());
                        } else if(frequencyVal=='Daily'){
                            Scheduler.setRunDateTime(1,today.getDate(),"",Scheduler.$scheduleTime.val());
                        } else if(frequencyVal=='Weekly'){
                            Scheduler.WeeklyCalendar.selectDay($(".weeksCol[data-numb="+(today.getDay()+1)+"]",$("#recuringWeekly")));
                            Scheduler.$recurringTime.val(today.getDay()+1);
                            Scheduler.setRunDateTime(2,"",today.getDay(),Scheduler.$scheduleTime.val());
                        }else if(frequencyVal=='Monthly'){
                            Scheduler.MonthlyCalendar.selectDay($("#recuringMonthly").find('.monthlyCalendar td[data-numb='+today.getDate()+']'));
                            Scheduler.$recurringTime.val(today.getDate());
                            Scheduler.setRunDateTime(3,today.getDate(),"",Scheduler.$scheduleTime.val());
                        }
                        populateSelectedReport();
                    });
                }
            },
            WeeklyCalendar : {
                $container : $(),
                init : function(_cont){
                    this.$container = _cont;
                    this.$container.hover(
                        function () {
                            $(this).addClass('weeksColHovered');
                        },
                        function () {
                            $(this).removeClass('weeksColHovered');
                        }
                    );
                    this.$container.click(function(){
                        Scheduler.WeeklyCalendar.selectDay($(this));
                        Scheduler.$recurringTime.val($(this).attr('data-numb'));
                        Scheduler.setRunDateTime(2,"",$(this).attr('data-numb')-1,Scheduler.$scheduleTime.val());
                        populateSelectedReport();
                    });
                },
                selectDay : function($day){
                    this.deselectAllDays();
                    $day.addClass('weeksColSelected');
                },
                deselectAllDays : function(){
                    this.$container.removeClass('weeksColSelected');
                }
            },
            $schedulerTimeFooter : "",
            $schedulerDateFooter : "",
            $scheduleTime : "",
            $scheduleDate : "",
            $scheduleDateParam : "",
            $recurringTime : "",

            init:function(){
                this.$schedulerTimeFooter = $("#schedulerFooter .schedulerTimeFooter");
                this.$schedulerDateFooter = $("#schedulerFooter .schedulerDateFooter");
                this.$scheduleTime = $("#scheduleTime");
                this.$scheduleDate = $("#scheduleDate");
                this.$scheduleDateParam = $("#scheduleDateParam");
                this.Recipients.init("#recipients");
                this.WeeklyCalendar.init($(".weeksCol",$("#recuringWeekly")));
                this.MonthlyCalendar.init($("#recuringMonthly").find(".monthlyCalendar td"));
                this.$recurringTime = $('#recuringTime');
                this.Frequency.init($("#frequency"));

                $(".recuringMonthlyOnTheContent, #monthlyGroupEach, #monthlyGroupOnThe, .recuringMonthlyOnTheHeader label").hide();
                $("#recuringDaily, #recuringWeekly> div:first, #recuringMonthly > div:first").css({"height":"34px","visibility":"hidden"});
            //datePicker
                this.$scheduleTime.timepicker({showButtonPanel:false, ampm:true, onClose: function(_dateText, _inst) {
                    var currTime = Date.parse(_dateText).toString("HH:mm");
                    Scheduler.$scheduleDateParam.val($.datepicker.formatDate('mm/dd/yy', new Date())+" "+currTime);
                    switch (Scheduler.Frequency.$itm.val()){
                        case "Daily":
                            var today = new Date();
                            Scheduler.setRunDateTime(1, today.getDate(), "", _dateText);
                            break;
                        case "Weekly":
                            Scheduler.setRunDateTime(2, "", Scheduler.$recurringTime.val()-1, _dateText);
                            break;
                        case "Monthly":
                            Scheduler.setRunDateTime(3, Scheduler.$recurringTime.val(), "", _dateText);
                            break;
                    }
                    populateSelectedReport();
                }});
                this.$scheduleTime.parent().hide();
                this.$scheduleDate.datetimepicker({showButtonPanel:false, ampm:true, dateFormat: 'mm/dd/yy', onClose: function(_dateText, _inst) {
                    var curDate = Date.parse(_dateText);
                    Scheduler.$scheduleDate.data("military",curDate.toString("HH:mm"));
                    Scheduler.$scheduleDate.data("date",_dateText.split(" ")[0]);

                    Scheduler.$scheduleDateParam.val(curDate.toString('MM/dd/yyyy HH:mm'));
                    Scheduler.Frequency.$itm.removeAttr("disabled");
                    Scheduler.$schedulerDateFooter.text(_dateText.split(" ")[0]);
                    Scheduler.$schedulerTimeFooter.text(curDate.toString("hh:mm tt").toLowerCase());
                    populateSelectedReport();
                }});
                if ($.trim(this.$scheduleDate.val())==""){
                    var execDate = new Date().add({minutes:1});
                    //var curTime=execDate.getHours()+":"+(execDate.getMinutes());
                    this.$scheduleDate.val(execDate.toString("MM/dd/yyyy hh:mm tt").toLowerCase());
                    this.$scheduleTime.val(execDate.toString("hh:mm tt").toLowerCase());
                }else{
                    this.$scheduleTime.val(Date.parse(this.$scheduleDate.val()).toString("hh:mm tt").toLowerCase());
                }
                this.$scheduleDateParam.val(Date.parse(this.$scheduleDate.val()).toString("MM/dd/yyyy HH:mm"));

            //After render
                this.Recipients.insertLoggedUserEmail();
                $("#selectedReportScheduler .selectedReportRecipientsText").text(this.Recipients.getRecipients());

                this.Frequency.$itm.val("<c:out value="${SCHEDULER_FREQUENCY}"/>");
                var freqDay = "<c:out value="${SCHEDULER_DAY}"/>";
                $('#recuringDaysCount<c:out value="${SCHEDULER_FREQUENCY}"/>').val('<c:out value="${SCHEDULER_RECURRING_COUNT}"/>');
                this.Frequency.$itm.change();
                var today=new Date();
                if (this.Frequency.$itm.val()=='OneTime'){

                }else if(this.Frequency.$itm.val()=="Daily"){
                    this.setRunDateTime(1,today.getDate(),"",Scheduler.$scheduleTime.val());
                }else if(this.Frequency.$itm.val()=="Weekly"){
                    Scheduler.WeeklyCalendar.selectDay($(".weeksCol[data-numb="+freqDay+"]",$("#recuringWeekly")));
                    Scheduler.$recurringTime.val(freqDay);
                    this.setRunDateTime(2,"",freqDay-1,Scheduler.$scheduleTime.val());
                }else if (this.Frequency.$itm.val()=='Monthly'){
                    Scheduler.MonthlyCalendar.selectDay($("#recuringMonthly").find('.monthlyCalendar td[data-numb='+freqDay+']'));
                    Scheduler.$recurringTime.val(freqDay);
                    this.setRunDateTime(3,freqDay,"",Scheduler.$scheduleTime.val());
                }

                populateSelectedReport();
            }
        };
        $(document).ready(function() {
            ReportDefinition.init(<c:out value='${IS_SCHEDULER_VISIBLE}'/>);
            TabParams.init();
            Scheduler.init();
        });
    </script>
</head>
<body>

<form id="reporting_form" method="post">
<div class="loadingMaskContainer">
	<div id="loadingMask"></div>
	<div class="aui-loadingmask-message"><div class="aui-loadingmask-message-content">Loading…</div></div>
</div>

<div id="container">
	<div class="spacer" style="width: 759px;">

	</div>
	<div id="tabs">
	<ul>
		<li><a href="#fragment-1"><span>Report</span></a></li>
		<li><a href="#fragment-2"><span>Type</span></a></li>
		<li><a href="#fragment-3"><span>Summary</span></a></li>
		<li><a href="#fragment-4"><span>Parameters</span></a></li>
		<li><a href="#fragment-5"><span>Output</span></a></li>
		<li><a href="#fragment-6"><span>Schedule</span></a></li>
	</ul>
	<div id="fragment-1">
		<mytag:tab_report />
	</div>
	<div id="fragment-2">
		<mytag:tab_type />
	</div>
	<div id="fragment-3">
		<mytag:tab_summary />
	</div>
	<div id="fragment-4">
		<mytag:tab_param />
	</div>
	<div id="fragment-5">
		<mytag:tab_output />
	</div>
	<div id="fragment-6">
		<mytag:tab_schedule />
	</div>
	</div>

	<div class="selected_report">
		<label>Defined Report</label>
		<div width="100%">
			<div class="selected_report_submit">
				<div><input type="button" id="cancelBtn" class="button" value="Cancel" onclick="gotoSubmit(this,'reportDefinition');" /></div>
				<div><input type="button" id="saveBtn" class="button" value="Save" onclick="validateSubmit(this);" /></div>
			</div>
			<div id="selectedReport" class="textContainer ui-corner-all">
                 <div class="selectedReportContentRight">
                    <input type="button" id="viewBtn" class="button" value="Run Now" onclick="gotoSubmit(this,'reportDefinition');" />
					<input type="button" id="scheduleBtn" class="button" value="Schedule" />
				</div>
				<div class="selectedReportContentLeft">
                    <span>
                        <span class='selectedReportBold'>Name: </span>
                        <span id="selectedReportName"><c:out value="${MY_REPORT_NAME}"></c:out></span>;
                    </span>
                    <c:if test='${DISPLAY_SELECTED_REPORT!=""}'>
						<span class='selectedReportBold'> Report: </span>
						<span><c:out value="${DISPLAY_SELECTED_REPORT}"></c:out></span>
					</c:if>
					<c:if test='${DISPLAY_SELECTED_TYPE!=""}'>
						<span class='selectedReportBold'>Type: </span>
						<span><c:out value="${DISPLAY_SELECTED_TYPE}"></c:out></span>
					</c:if>
					<c:if test='${DISPLAY_SELECTED_SUMMARY!=""}'>
						<span class='selectedReportBold'>Summary: </span>
						<span><c:out value="${DISPLAY_SELECTED_SUMMARY}"></c:out></span>
					</c:if>
					<c:choose>
						<c:when test='${DISPLAY_SELECTED_PARAMETERS!=""}'>
							<div id="paramsDiv">
								<span class='selectedReportBold'>Parameters: </span>
								<span id="paramList"></span>
							</div>
						</c:when>
						<c:otherwise>
							<div id="paramsDiv" style="display:none">
								<span class='selectedReportBold'>Parameters: </span>
								<span id="paramList"></span>
							</div>
						</c:otherwise>
					</c:choose>
					<c:if test='${DISPLAY_SELECTED_OUTPUT!=""}'>
						<span class='selectedReportBold'>Output: </span>
						<span><c:out value="${DISPLAY_SELECTED_OUTPUT}"></c:out></span>
					</c:if>
                    <span id="selectedReportScheduler">
                        <span class='selectedReportBold'>Schedule: </span>
                        <span class="selectedReportScheduleText"></span>;
                        <span class='selectedReportBold'>Recipients: </span>
                        <span class="selectedReportRecipientsText"><c:out value="${SCHEDULER_EMAIL}"></c:out></span>;
                    </span>
				</div>
			</div>
		</div>
	</div>
</div>

<input id='sTab' type="hidden" value=<c:out value='${TAB_SELECTED}'/> />
</form>
<input id="formAction" type="hidden" value="<portlet:actionURL/>" />
<input type="hidden" id="isViewPressed" value=<c:out value="${isViewPressed}"/> />
</body>
</html>
